package com.lxl.workbench.controller;

import com.alibaba.fastjson.JSON;
import com.lxl.commons.contants.BaseServlet;
import com.lxl.commons.contants.Contants;
import com.lxl.commons.domain.ReturnObject;
import com.lxl.commons.utils.Md5;
import com.lxl.commons.utils.UUIDUtils;
import com.lxl.settings.entity.User;
import com.lxl.workbench.entity.Category;
import com.lxl.workbench.entity.CategoryStaff;
import com.lxl.workbench.entity.CommonStaff;
import com.lxl.workbench.service.CategoryService;
import com.lxl.workbench.service.StaffService;
import com.lxl.workbench.service.impl.CategoryServiceImpl;
import com.lxl.workbench.service.impl.StaffServiceImpl;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author 北上寻海
 */
@WebServlet({"/selectStaff","/selectCommonStaff","/promoteStaff","/demoteStaff","/resignStaff","/addCommonStaff","/addCategoryStaff"})
public class StaffServlet extends BaseServlet {

    /**
     * 需要用到的service对象，员工，书目
     * 专门用于返回数据给前台页面的对象ReturnObject
     */
    StaffService staffService = new StaffServiceImpl();
    CategoryService categoryService = new CategoryServiceImpl();
    ReturnObject returnObject = new ReturnObject();

    /**
     *根据条件筛选，模糊查询员工，包括普通员工和书目管理员
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void selectStaffByCondition(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        List<Object> list = new ArrayList<>();
        //获取前端传过来的查询条件
        String staffName = request.getParameter("staffName");
        String staffSex = request.getParameter("staffSex");
        String staffType = request.getParameter("staffType");
        //在controller判断要查哪个表，如果没有填类型那就是查两个表
        if ("".equals(staffType) || staffType == null) {
            try {
                List<CategoryStaff> categoryStaffList = staffService.queryStaffFromCategory(staffName, staffSex);
                List<CommonStaff> commonStaffList = staffService.queryStaffFromCommon(staffName, staffSex);
                //判断查询结果集是否为空
                boolean judge1 = categoryStaffList != null && !categoryStaffList.isEmpty();
                boolean judge2 = commonStaffList != null && !commonStaffList.isEmpty();
                if (judge1 || judge2) {
                    if (judge1) {
                        for (CategoryStaff categoryStaff : categoryStaffList) {
                            categoryStaff.setPermissions(Contants.CATEGORY_STAFF);
                        }
                    }
                    if (judge2) {
                        for (CommonStaff commonStaff : commonStaffList) {
                            commonStaff.setPermissions(Contants.COMMON_STAFF);
                        }
                    }
                    //将普通员工和书目管理员一起封装到list放进returnObject的retData属性里面
                    list.add(categoryStaffList);
                    list.add(commonStaffList);
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                    returnObject.setMessage("查询成功");
                    returnObject.setRetData(list);
                } else {
                    returnObject.setMessage("查无此人");
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                }
            } catch (SQLException e) {
                e.printStackTrace();
                returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            }
            //条件筛选中的员工类型为普通员工时，直接查普通员工表
        } else if (Contants.COMMON_STAFF.equals(staffType)) {

            try {
                List<CommonStaff> commonStaffList = staffService.queryStaffFromCommon(staffName, staffSex);
                if (commonStaffList != null && !commonStaffList.isEmpty()) {
                    for (CommonStaff commonStaff : commonStaffList) {
                        commonStaff.setPermissions(Contants.COMMON_STAFF);
                    }
                    list.add(commonStaffList);
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                    returnObject.setMessage("查询成功");
                    returnObject.setRetData(list);
                } else {
                    returnObject.setMessage("查无此人");
                    returnObject.setMessage(Contants.RETURN_OBJECT_CODE_FAIL);
                }
            } catch (SQLException e) {
                e.printStackTrace();
                returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
                returnObject.setMessage(Contants.RETURN_OBJECT_CODE_FAIL);
            }
            //条件筛选中的员工类型为书目管理员时，直接查书目管理员表
        } else if (Contants.CATEGORY_STAFF.equals(staffType)) {
            try {
                List<CategoryStaff> categoryStaffList = staffService.queryStaffFromCategory(staffName, staffSex);
                for (CategoryStaff categoryStaff : categoryStaffList) {
                    categoryStaff.setPermissions(Contants.CATEGORY_STAFF);
                }
                list.add(categoryStaffList);
                if (!categoryStaffList.isEmpty()) {
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                    returnObject.setMessage("查询成功");
                    returnObject.setRetData(list);
                } else {
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                    returnObject.setMessage("查无此人");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
            }
        }
        //转成json形式返回
        String json = JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }


    /**
     * 升职，先查一查选的是不是普通员工，是的话把员工信息也拿出来，后面封装成书目管理员
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void selectCommonStaffById(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String staffId = request.getParameter("staffId").replace("/","");
        try {
            List<CommonStaff> commonStaffList = staffService.selectCommonStaffById(staffId);
            if(commonStaffList!=null&&commonStaffList.size()>0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(commonStaffList.get(0));
                //打印查出来的commonStaff对象
               // System.out.println(returnObject.getRetData());
            }else {
                returnObject.setMessage("请选择一名普通员工");
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            }
        } catch (SQLException e) {
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
            e.printStackTrace();
        }
        String json = JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }

    /**
     *员工升职，删普通员工，加书目管理员
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void promoteStaffByCondition(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        try {
            //这个是填的书目，要把它的id查出来先
            List<Category> categoryList = categoryService.selectCategoryId(request.getParameter("category"));
            if(categoryList!=null&&categoryList.size()>0){
                String manageTypeId = categoryList.get(0).getId();
                String id =   request.getParameter("id");
                //将数据封装成书目管理员
                CategoryStaff categoryStaff = new CategoryStaff(
                        id,
                        request.getParameter("staffName"),
                        request.getParameter("gender"),
                        request.getParameter("phone"),
                        manageTypeId,
                        Contants.CATEGORY_STAFF_PERMISSIONS,
                        request.getParameter("userId")
                        //往下就是删数据的操作了，普通员工表，根据id删，书目管理员表，根据categoryStaff加
                );
                    staffService.promoteStaff(categoryStaff,id);
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                    returnObject.setMessage("调度成功");
            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("您分配的书目不存在！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }
        //转为json，发送给前端页面
        String json = JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }


    /**
     * 根据选择的id，辞退员工，员工有两个种，所有两个表都要操作
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void resignStaffByIds(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String []  delIds = request.getParameter("ids").replace("/","").split(",");
        //先把userId查出来，再一起发送删除请求
        try {
            List<CommonStaff> commonStaffList = staffService.selectCommonStaffForUserId(delIds);
            List<CategoryStaff> categoryStaffList = staffService.selectCategoryStaffForUserId(delIds);
            //装userIds的数组
            String [] userIds = new String[categoryStaffList.size()+commonStaffList.size()];
            if(categoryStaffList.size()>0){
                for(int i = 0;i<categoryStaffList.size();i++){
                    userIds[i] = categoryStaffList.get(i).getUserId();
                }
            }
            if(commonStaffList.size()>0){
                for(int i = categoryStaffList.size();i<categoryStaffList.size()+commonStaffList.size();i++){
                    userIds[i] = commonStaffList.get(i).getUserId();
                }
            }
            staffService.resignStaffByIds(delIds,userIds);
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setMessage("删除成功");
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }
        //转json，返回给前端
        String json = JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }

    /**
     * 降职，删书目管理员，加普通员工
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void demoteStaffByIds(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String [] ids = request.getParameter("ids").replace("/","").split(",");
        try {
            List<CategoryStaff> categoryStaffList = staffService.selectCategoryStaffForUserId(ids);
            List<CommonStaff> commonStaffList = new ArrayList<>();
            String [] categoryIds = new String[categoryStaffList.size()];
            if(categoryStaffList!=null&&categoryStaffList.size()>0){
                for(int i = 0;i<categoryStaffList.size();i++){
                    CommonStaff commonStaff = new CommonStaff();
                    commonStaff.setId(categoryStaffList.get(i).getId());
                    commonStaff.setStaffName(categoryStaffList.get(i).getStaffName());
                    commonStaff.setGender(categoryStaffList.get(i).getGender());
                    commonStaff.setPhone(categoryStaffList.get(i).getPhone());
                    commonStaff.setUserId(categoryStaffList.get(i).getUserId());
                    commonStaff.setPermissions(Contants.COMMON_STAFF_PERMISSIONS);
                    categoryIds[i] = categoryStaffList.get(0).getId();
                    commonStaffList.add(commonStaff);
                }
            }
            try {
                staffService.demoteStaffByIds(commonStaffList,categoryIds);
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("调度成功");
            }catch (SQLException e){
                e.printStackTrace();
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }
        //转json，返回给前端
        String json = JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }


    /**
     * 添加普通员工
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void addCommonStaffByCondition  (HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        //添加普通员工，要加用户表和普通员工表
        //用户表
        String userId = UUIDUtils.getUuid();
        User user = new User(userId,
                request.getParameter("commonAccount"),
                Md5.md5(request.getParameter("commonPassword")));
        String commonStaffId = UUIDUtils.getUuid();
        //普通员工表
        CommonStaff commonStaff = new CommonStaff(commonStaffId,
                request.getParameter("commonStaffName"),
                request.getParameter("commonGender"),
                request.getParameter("commonPhone"),
                userId,
                Contants.COMMON_STAFF_PERMISSIONS);
        try {
            staffService.addCommonStaffByCondition(user,commonStaff);
            commonStaff.setPermissions(Contants.COMMON_STAFF);
            returnObject.setMessage(""+commonStaff.getStaffName()+"添加成功");
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setRetData(commonStaff);
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
        }
        //转json，返回给前端
        String json = JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }

    /**
     * 添加书目管理员
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void addCategoryStaffByCondition  (HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        //User用户表
        String userId = UUIDUtils.getUuid();
        User user = new User(userId,
                request.getParameter("categoryAccount"),
                Md5.md5(request.getParameter("categoryPassword")));
       // System.out.println(user);
        //书目管理员

        try {
             List<Category> categoryList = categoryService.selectCategoryId(request.getParameter("categoryManageType"));
             if(categoryList.size()>0) {

                 String categoryManageTypeId = categoryList.get(0).getId();
                 String categoryStaffId = UUIDUtils.getUuid();
                 CategoryStaff categoryStaff = new CategoryStaff(
                         categoryStaffId,
                         request.getParameter("categoryStaffName"),
                         request.getParameter("categoryGender"),
                         request.getParameter("categoryPhone"),
                         categoryManageTypeId,
                         Contants.CATEGORY_STAFF_PERMISSIONS,
                         userId);
                 try {
                     staffService.addCategoryStaffByCondition(user,categoryStaff);
                     categoryStaff.setPermissions(Contants.CATEGORY_STAFF);
                     returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                     returnObject.setMessage("添加成功");
                     returnObject.setRetData(categoryStaff);
                 } catch (SQLException e) {
                     e.printStackTrace();
                     returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                     returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
                 }
             }else {
                 returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                 returnObject.setMessage("该书目不存在");
             }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }

        //转json，返回给前端
        String json = JSON.toJSONString(returnObject);
        response.getWriter().write(json);
    }


}

